<?php

namespace app\service;

use think\Exception;
use support\ErrorCode;
use support\UCenterService;
use teamones\filter\Enforcer;
use think\db\exception\DbException;
use app\service\Member as MemberService;
use app\model\PostRecord as PostRecordModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class PostRecord
{


    /**
     * 创建文件记录
     * @param $data
     * @return PostRecordModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function create($data)
    {
        $postRecord = PostRecordModel::where(['post_id' => $data['post_id'], 'user_id' => $data['user_id'], 'tenant_id' => $data['tenant_id']])->find();
        if ($postRecord) {
            return PostRecordModel::update($data, ['id' => $postRecord['id']]);
        } else {
            $data['updated'] = time();
            return PostRecordModel::create($data);
        }
    }


    /**
     *  更新文件记录
     * @param $data
     * @return PostRecordModel|void
     * @throws \exception
     */
    public function update($data)
    {
        $postRecord = new PostRecordModel();
        $postRecordOne = $postRecord->find((int)$data['id']);
        if ($postRecordOne && $data['operation'] == 'open') {
            return PostRecordModel::update($data, ['id' => $data['id']]);
        } else if ($postRecordOne && $data['operation'] == 'edit') {
            return PostRecordModel::update(['updated' => time()], ['id' => $data['id']]);
        }
    }


    /**
     * 查询文件记录
     * @param $filter
     * @param $userId
     * @param $tenantId
     * @return array|array[]|void
     * @throws \exception
     */
    public function select($filter, $userId, $tenantId)
    {
        try {
            $postRecordList = PostRecordModel::where(['post_record.tenant_id' => $tenantId, 'user_id' => $userId])->withJoin([
                'post' => ['created_by', 'name', 'file_type']
            ], 'Left');
            if (isset($filter['filter']['file_type'])) {
                $postRecordList->where('file_type', $filter['filter']['file_type']);
            }
            if (isset($filter['filter']['title'])) {
                $postRecordList->where('name', 'like', '%' . $filter['filter']['title'] . '%');
            }
            if ($filter['filter']['recently'] == 'open') {
                $postRecordList->order('last_open_time', 'desc');
            } else if ($filter['filter']['recently'] == 'edit') {
                $postRecordList->order('updated', 'desc');
            }
            $page = $filter['page'] ?? [1, 20];
            $rows = $postRecordList->page($page[0], $page[1])->select()->toArray();

            if (!empty($rows)) {
                // 获取当前用户角色
                $memberService = new MemberPer();
                $recordRole = $memberService->getFileRecordRole($userId, $tenantId, array_column($rows, 'id'));
                foreach ($rows as $k => $v) {
                    $rows[$k]['role'] = $recordRole[$v['id']] ?? 'viewer';
                }
            }

            $postList = array_column($rows, 'post', 'id');
            $createdByIdList = array_column($postList, 'created_by', 'created_by');
            if (!empty($createdByIdList)) {
                // 使用用户中心服务类远程调用查询出$createdByIdList下的所有对应用户信息
                $users = UCenterService::getInstance()->tenantUser->selectTenantUser([
                    'param' => [
                        'filter' => [
                            'tenant_user.tenant_id' => $tenantId,
                            'tenant_user.user_id' => ['-in', implode(',', $createdByIdList)],
                        ],
                        'fields' => 'user.id,user.name'
                    ]
                ]);
                if ($users['total'] > 0) {
                    // 处理用户信息集给其中每一个数组赋值新的键值user_id
                    $users = array_map(function ($item) {
                        $item['user_id'] = $item['user']['id'];
                        return $item;
                    }, $users['rows']);
                    // 将user_id作为$users新的索引/键
                    $usersMap = array_column($users, null, 'user_id');
                    $rows = array_map(function ($item) use (&$usersMap) {
                        if (array_key_exists($item['post']['created_by'], $usersMap)) {
                            $item['post']['created_by'] = $usersMap[$item['post']['created_by']]['user']['name'];
                        } else {
                            $item['post']['created_by'] = "";
                        }
                        return $item;
                    }, $rows);
                }
            }
            return $rows;
        } catch (\Throwable $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::SELECT_POSTRECORD_FAILURE);
        }
    }

    /**
     * 查找文件记录
     * @param $filter
     * @param $tenantId
     * @param $userId
     * @return PostRecordModel
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function find($filter, $tenantId, $userId)
    {
        $postRecordFilter['user_id'] = $userId;
        $postRecordFilter['post_id'] = $filter['post_id'] ?? 0;
        $res = PostRecordModel::where(Enforcer::parseWhere($postRecordFilter))->withJoin([
            'post' => ['created_by', 'name', 'file_type']
        ], 'Left')->find();
        if (empty($res)) {
            $postId = $filter['post_id'] ?? 0;
            $globalId = $filter['global_id'] ?? '';
            if (empty($postId) || empty($globalId)) {
                throw new Exception('File Record is null', ErrorCode::FIND_POSTRECORD_FAILURE);
            }
            $chat = UCenterService::getInstance()->chat->find([
                'param' => [
                    'filter' => [
                        'chat.global_id' => $globalId
                    ],
                    'fields' => 'global_id,name,type'
                ]
            ]);
            $chatName = '';
            if ($chat['chat']['type'] == 'one2one') {
                $chatIds = explode('&', $globalId);
                if ($key = array_search($userId, $chatIds)) {
                    unset($chatIds[$key]);
                }
                $userInfo = UCenterService::getInstance()->user->getOtherUserInfo([
                    'user_id' => $chatIds[0]
                ]);
                $chatName = "单聊：" . $userInfo['user']['name'];
            } else if ($chat['chat']['type'] == 'group') {
                $chatName = "群聊：" . $chat['chat']['name'];
            }
            $postRecord = [
                'post_id' => $postId,
                'user_id' => $userId,
                'updated' => time(),
                'chat_name' => $chatName,
                'tenant_id' => $tenantId,
                'chat_global_id' => $globalId
            ];
            $res = PostRecordModel::create($postRecord);
        }
//        $memberService = new MemberPer();
//        $recordRole = $memberService->getFileRecordRole($userId, $tenantId, [$res['id']]);
//        $res['role'] = $recordRole[$res['id']] ?? 'viewer';
        // 文件记录,谁打开谁就是创建者
        $res['role'] = 'super_admin';
        $usersService = new MemberService();
        $userInfo = $usersService->getUserInfo([$res['post']['created_by']]);
        if (!empty($userInfo['data']['rows'][0]['name'])) {
            $res['post']['created_by'] = $userInfo['data']['rows'][0]['name'];
        }
        return $res;
    }

    /**
     * 删除文件记录
     * @param $filter
     * @return bool
     * @throws DbException
     * @throws \Throwable
     */
    public function delete($filter)
    {
        return PostRecordModel::where('id', $filter['filter']['id'])->delete();
    }
}
